<!-- /**
 * @description: 原版：数据查询页面
 * @return {*}
 */ -->
<template>
  <div>
    <CustomTable
      ref="customTableRef"
      url="/file/search/company-list"
      :searchInfo="searchInfo"
      methods="post"
      :fn="formatData"
      :loading="true"
      @reset="reset"
      :params="{ ...state.exportCntArea }"
      :columns="columns"
    >
      <template #synced="{ data }">
        <el-tag :type="data.synced ? 'primary' : 'danger'">
          {{ data.synced ? "已同步" : "未同步" }}
        </el-tag>
      </template>
      <template #exportCntArea>
        <div class="df jcsb w200">
          <el-input
            controls-position="right"
            size="small"
            :step="1"
            @change="changeexportCntMin"
            style="width: 84px"
            placeholder="请输入"
            :min="0"
            v-model="state.exportCntArea.exportCntMin"
            type="number"
          ></el-input>
          ～
          <el-input
            size="small"
            :step="1"
            @change="changeexportCntMax"
            controls-position="right"
            style="width: 84px"
            placeholder="请输入"
            :min="0"
            v-model="state.exportCntArea.exportCntMax"
            type="number"
          ></el-input>
        </div>
      </template>
      <template #searchAfter="data">
        <div class="dib upload-0023 ml10">
          <el-button size="small" @click="handleDataSummary" type="success"
            >数据汇总</el-button
          >
          <!-- <DictUpload  :limit="300" :isShowTip="false" :fileSize="100" :fileType='["xls","xlsx","excel"]'></DictUpload>   -->
        </div>
        <div class="dib upload-0023 ml10">
          <el-button
            size="small"
            @click="handleExport(data, false)"
            type="warning"
            >导出</el-button
          >

          <el-button
            size="small"
            @click="handleExport(data, true)"
            type="primary"
            >同步数据</el-button
          >
          <!-- <DictUpload  :limit="300" :isShowTip="false" :fileSize="100" :fileType='["xls","xlsx","excel"]'></DictUpload>   -->
        </div>
      </template>
      <template #exported="{ data }">
        <div class="dib">
          {{ data.exported ? "是" : "否" }}
          <!-- <DictUpload  :limit="300" :isShowTip="false" :fileSize="100" :fileType='["xls","xlsx","excel"]'></DictUpload>   -->
        </div>
      </template>
    </CustomTable>

    <!-- 同步/导出：弹框 -->
    <el-dialog
      :title="state.sync ? '同步数据' : '导出数据'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="800px"
      v-model="state.visible"
    >
      <exportFile v-if="state.visible"></exportFile>
      <slot></slot>
    </el-dialog>

    <!-- 数据汇总：弹框 -->
    <el-drawer size="800px" title="数据汇总" v-model="state.summryVisible">
      <summaryData v-if="state.summryVisible"></summaryData>
    </el-drawer>
  </div>
</template>
<script setup>
import { ref, reactive, provide, onMounted } from "vue";
import exportFile from "./components/exportFile.vue";
import summaryData from "./components/summaryData.vue";
import { getProvincStatistics, getBatchName } from "@/api/uploadFile.js";
onMounted(() => {
  getBatchName().then((res) => {
    res.data = res.data || [];
    res?.data.forEach((i) => {
      i.label = i.batchName;
      i.value = i.batchName;
    });
    searchInfo.value.forEach((_) => {
      if (_.key === "batchName") {
        _.options = res.data;
      }
    });
  });
});

const customTableRef = ref();
const { proxy } = getCurrentInstance();
const provinces = proxy.getProvinces();
provinces.forEach((_) => {
  _.label = _.name;
  _.value = _.name;
});
const columns = ref([
  {
    prop: "id",
    label: "id",
    width: "100",
    fixed: "left",
  },
  {
    prop: "companyName",
    width: 260,
    label: "企业名称",
    fixed: "left",
  },
  {
    prop: "phoneNum",
    width: 169,
    label: "手机号",
  },
  //   {
  //     prop: 'riskLevel',
  //     label: '风险等级',
  //   },
  {
    prop: "legalPerson",
    minWidth: 100,
    label: "导入法人",
  },
  {
    prop: "checkLegal",
    label: "校对法人",
  },
  {
    prop: "legalPercent",
    label: "法人占股比例",
  },
  {
    prop: "consistence",
    label: "一致性",
  },
  {
    prop: "postName",
    minWidth: 100,
    label: "类型",
  },
  {
    prop: "province",
    minWidth: 100,
    label: "省",
  },
  {
    prop: "city",
    minWidth: 100,
    label: "市",
  },
  {
    prop: "area",
    minWidth: 80,
    label: "区",
  },
  {
    prop: "entstatusName",
    label: "在营状态",
  },
  // {
  //   prop: "",
  //   label: "注册时间",
  // },
  {
    prop: "regCap",
    label: "注册资金",
  },
  // 没给值
  // {
  //   prop: "paidcap",
  //   label: "实缴资金",
  // },
  {
    prop: "industryphy",
    label: "一级行业",
  },
  {
    prop: "industryphy1",
    label: "二级行业",
  },
  {
    prop: "industryphy2",
    label: "三级行业",
  },
  // 暂无
  // {
  //   prop: 'enttypeName',
  //   label: ''
  // },
  {
    prop: "creditCode",
    label: "信用代码",
  },
  {
    prop: "batchName",
    label: "批次",
  },
  {
    prop: "createTime",
    width: 132,
    label: "创建时间",
  },
  {
    prop: "updateTime",
    width: 132,
    label: "更新时间",
  },
  // {
  //   prop: '',
  //   label: '点呼导出次数',
  // },
  // {
  //   prop: '',
  //   label: '群呼导出次数',
  // },
  // {
  //   prop: '',
  //   label: 'AI导出次数',
  // },
  // {
  //   prop: '',
  //   label: '同步推送'
  // }

  // 以下字段是之前版本
  // {
  //   prop: "exportCnt",
  //   minWidth: 112,
  //   label: "导出次数",
  // },
  // {
  //   prop: "exported",
  //   minWidth: 112,
  //   label: "是否导出",
  // },
  // {
  //   prop: "synced",
  //   minWidth: 112,
  //   label: "是否同步",
  // },
]);
const changeexportCntMin = (e) => {
  console.log(state.exportCntArea.exportCntMax, typeof e);
  if (
    state.exportCntArea.exportCntMin &&
    state.exportCntArea.exportCntMin.includes(".")
  ) {
    const index = state.exportCntArea.exportCntMin.indexOf(".");
    console.log(index);
    state.exportCntArea.exportCntMin = state.exportCntArea.exportCntMin.slice(
      0,
      index + 3
    );
  }
  if (state.exportCntArea.exportCntMax !== "" && e !== "") {
    if (Number(state.exportCntArea.exportCntMax) < Number(e)) {
      state.exportCntArea.exportCntMax = "";
    }
  }
};
const reset = () => {
  state.exportCntArea.exportCntMin = "";
  state.exportCntArea.exportCntMax = "";
};
const changeexportCntMax = (e) => {
  if (
    state.exportCntArea.exportCntMax &&
    state.exportCntArea.exportCntMax.includes(".")
  ) {
    const index = state.exportCntArea.exportCntMax.indexOf(".");
    state.exportCntArea.exportCntMax = state.exportCntArea.exportCntMax.slice(
      0,
      index + 3
    );
  }
  if (state.exportCntArea.exportCntMax !== "" && e !== "") {
    if (Number(state.exportCntArea.exportCntMin) > Number(e)) {
      state.exportCntArea.exportCntMin = "";
    }
  }
};

const handleDataSummary = () => {
  state.summryVisible = true;
};

const state = reactive({
  sync: false,
  limitInfo: {
    number: 0,
    editorableData: [], // table  可编辑的数据的数量
    frozenNumber: 0,
  },
  postNames: [
    { label: "A", value: "A" },
    { label: "B", value: "B" },
    { label: "C", value: "C" },
    { label: "N", value: "N" },
  ],
  exportDataCount: [], // 导出数据
  exportDataLoading: false,
  translate(val, key) {
    val[key] = val[key] ? val[key].toString() : null;
  },

  visible: false,
  summryVisible: false,
  id: null,
  exportCntArea: {
    exportCntMin: "",
    exportCntMax: "",
  },
  getParams: () => {
    console.log(state.exportCntArea);
    const obj = {
      ...state.exportCntArea,
      ...customTableRef.value.state.params,
    };
    const { pageNum, pageSize, exportCntArea, ...params } = obj;
    return params;
  },
  getPagination: () => {
    const obj = {
      ...customTableRef.value.state.params,
    };
    const { pageNum, pageSize } = obj;
    return { pageNum, pageSize };
  },
});

const formatData = (res) => {
  const params = state.getParams();
  const limitCnt = (params.limitCnt ?? 0) * 1;
  const { pageNum, pageSize } = state.getPagination();
  if (limitCnt !== 0 && typeof limitCnt === "number" && limitCnt <= res.total) {
    res.total = limitCnt;
    if (res.rows) {
      console.log(pageNum, pageSize);
      if (pageNum * pageSize > limitCnt) {
        res.rows = res.rows.splice(0, limitCnt % pageSize);
        console.log(limitCnt % pageSize, res.rows, "dddff");
      }
    }
    if (res.rows && res.rows.length > limitCnt) {
      res.rows = res.rows.splice(0, limitCnt);
    }
  }
};

const handleExport = (data, sync = false /** true 同步 ；false 导出 */) => {
  state.sync = sync;
  state.exportDataCount = [];
  state.limitInfo.frozenNumber = 0;
  state.limitInfo.number = 0;
  console.log(data.scope);
  state.visible = true;
  state.exportDataLoading = true;
  const params = state.getParams();
  state.translate(params, "postName");
  state.translate(params, "province");
  state.translate(params, "batchName");
  params.synced = sync === true ? false : null; // 同步时传false 选择非同步的数据 ，导出不传
  getProvincStatistics(params)
    .then((res) => {
      state.exportDataLoading = false;
      const par =
        /^浙江|上海|北京|天津|重庆|黑龙江|吉林|辽宁|内蒙古|河北|新疆|甘肃|青海|陕西|宁夏|河南|山东|山西|安徽|湖北|湖南|江苏|四川|贵州|云南|广西|西藏|江西|广东|福建|台湾|海南|香港|澳门$/;
      const obj = {};

      state.limitInfo.number = 0;
      state.limitInfo.frozenNumber = 0;
      state.limitInfo.editorableData = [];
      const numberArea = { min: 0, min: 0 };
      res.data.forEach((_) => {
        if (_.province) {
          if (_.count) {
            state.limitInfo.editorableData.push(_);
          }
          state.limitInfo.number += _.count * 1;
          state.limitInfo.frozenNumber += _.count * 1;
          console.log(_, state.limitInfo.number);
          if (obj[_.province]) {
            Object.assign(obj[_.province], {
              province: _.province,
              [_.postName]: _.count,
              ["count" + _.postName]: _.count,
            });
          } else {
            obj[_.province] = {
              province: _.province,
              [_.postName]: _.count,
              ["count" + _.postName]: _.count,
            };
          }
        }
      });
      state.exportDataCount = Object.values(obj) || [];
    })
    .finally((e) => {
      state.exportDataLoading = false;
    });
};

const searchInfo = ref([
  // { key: 'companyName', label: '企业名称' },
  {
    key: "province",
    label: "省份",
    type: "select",
    collapseTagsTooltip: false,
    collapseTags: false,
    options: [...provinces],
    multiple: true,
    translate(val, key) {
      state.translate(val, key);
    },
  },
  {
    key: "postName",
    label: "类型",
    multiple: true,
    type: "select",
    options: state.postNames,
    translate(val, key) {
      state.translate(val, key);
    },
  },
  {
    key: "exported",
    label: "是否导出",
    type: "select",
    options: [
      { label: "是", value: true },
      { label: "否", value: false },
    ],
  },
  {
    key: "synced",
    label: "是否同步",
    type: "select",
    options: [
      { label: "已同步", value: true },
      { label: "未同步", value: false },
    ],
  },
  {
    key: "exportCntArea",
    label: "导出次数",
    type: "slot",
    keys: ["exportCntMin", "exportCntMax"],
  },

  {
    key: "batchName",
    label: "批次",
    type: "select",
    collapseTagsTooltip: false,
    collapseTags: false,
    options: [],
    multiple: true,
    translate(val, key) {
      state.translate(val, key);
    },
  },
  {
    key: "limitCnt",
    width: "200px",
    type: "inputNumber",
    label: "数据限制",
    defaultValue: 100000,
    max: 2147483647,
  },
  {
    key: "queryDate",
    label: "查询周期",
    type: "dateRange",
    keys: ["createTimeStart", "createTimeEnd"],
  },
]);

provide("state", state);
</script>
<style scoped>
/* ::v-deep(.el-upload__tip){display:none} */

::v-deep(.el-pagination__jump) {
  display: none;
}
</style>
